package com.fescoservice.dao;

// default package

import java.sql.SQLException;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Hibernate;
import org.hibernate.HibernateException;
import org.hibernate.LockMode;
import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.springframework.context.ApplicationContext;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.fescoservice.exception.FSException;
import com.fescoservice.model.BBS;
import com.fescoservice.model.BBSId;
import com.fescoservice.model.CategoryId;

/**
 * A data access object (DAO) providing persistence and search support for BBS
 * entities. Transaction control of the save(), update() and delete() operations
 * can directly support Spring container-managed transactions or they can be
 * augmented to handle user-managed Spring transactions. Each of these methods
 * provides additional information for how to configure it for the desired type
 * of transaction control.
 * 
 * @see .BBS
 * @author MyEclipse Persistence Tools
 */

public class BBSDAO extends HibernateDaoSupport {
	private static final Log log = LogFactory.getLog(BBSDAO.class);
	// property constants
	public static final String DEFAULT_YN = "defaultYn";
	public static final String TITLE = "title";
	public static final String USER_ID = "userId";
	public static final String TOP_SEQ = "topSeq";
	public static final String PARENT_SEQ = "parentSeq";
	public static final String SORT_SEQ = "sortSeq";
	public static final String HITS = "hits";
	public static final String ATTACH_YN = "attachYn";
	public static final String IS_EDITOR = "isEditor";
	public static final String LOCALE = "locale";
	public static final String CHARSET = "charset";
	public static final String SUMMARY = "summary";
	public static final String FOCUS_YN = "focusYn";
	public static final String STATUS = "status";

	protected void initDao() {
		// do nothing
	}

	public void save(BBS transientInstance) {
		log.debug("saving BBS instance");
		try {
			getHibernateTemplate().save(transientInstance);
			log.debug("save successful");
		} catch (RuntimeException re) {
			log.error("save failed", re);
			throw re;
		}
	}
	
	public void update(BBS transientInstance) {
		log.debug("update BBS instance");
		try {
			getHibernateTemplate().update(transientInstance);
			log.debug("update successful");
		} catch (RuntimeException re) {
			log.error("update failed", re);
			throw re;
		}
	}

	public void delete(BBS persistentInstance) {
		log.debug("deleting BBS instance");
		try {
			getHibernateTemplate().delete(persistentInstance);
			log.debug("delete successful");
		} catch (RuntimeException re) {
			log.error("delete failed", re);
			throw re;
		}
	}

	public Long countBBSId(final String sql ,final BBSId id) throws FSException{
		log.debug("finding Category instance by example");
		try {
			Long count = (Long) getHibernateTemplate().execute(
					   new HibernateCallback() {
					   public Object doInHibernate(Session session)
					   throws HibernateException, SQLException {
						   SQLQuery q = session.createSQLQuery(sql);
						   q.setString("boardCode1" , id.getBoardCode1());   
						   q.setString("boardCode2" , id.getBoardCode2());   
						   q.setString("boardCode3" , id.getBoardCode3()); 
						  return q.addScalar( "cnt" , Hibernate.LONG).uniqueResult();
					   }
					 } );
			return count;
		} catch (Exception re) {
			log.error("count categories failed", re);
			throw new FSException("FS_ERROR_COUNTBBS",re.getMessage());
		}
	}
	
	public List findBBSByCategory(final String hql,final CategoryId categoryId)  throws FSException{
		try {
			List result = (List) getHibernateTemplate().execute(
					   new HibernateCallback() {
					   public Object doInHibernate(Session session)
					   throws HibernateException, SQLException {
						   Query q = session.createQuery(hql);
						   q.setString("boardCode1" , categoryId.getBoardCode1());   
						   q.setString("boardCode2" , categoryId.getBoardCode2());   
						   q.setString("boardCode3" , categoryId.getBoardCode3());   
						  return q.list();
					   }
					 } );
			return result;
		} catch (RuntimeException re) {
			log.error("get code1names failed", re);
			throw new FSException("FS_ERROR_GETCODE2NAMES",re.getMessage());
		}
	}
	
	public void updateDefault(final String hql,final String boardcode1,final String boardcode2,final String boardcode3) throws FSException{
		getHibernateTemplate().execute(new HibernateCallback() {
			public Object doInHibernate(Session session) throws SQLException,
					HibernateException {
					Query q = session.createQuery(hql); 
					   q.setString("boardCode1" , boardcode1);   
					   q.setString("boardCode2" , boardcode2); 					   
					   q.setString("boardCode3" , boardcode3); 
					q.executeUpdate();
				return null;
			}
		});
	}		

	public void deleteBBS(final String hql,final BBSId id) throws FSException{
		getHibernateTemplate().execute(new HibernateCallback() {
			public Object doInHibernate(Session session) throws SQLException,
					HibernateException {
					Query q = session.createQuery(hql); 
					   q.setString("boardCode1" , id.getBoardCode1());   
					   q.setString("boardCode2" , id.getBoardCode2()); 					   
					   q.setString("boardCode3" , id.getBoardCode3()); 					   
					   q.setLong("boardSeq" , id.getBoardSeq());  
					q.executeUpdate();
				return null;
			}
		});
	}	

	public BBS findById(BBSId id) {
		log.debug("getting BBS instance with id: " + id);
		try {
			BBS instance = (BBS) getHibernateTemplate().get("com.fescoservice.model.BBS", id);
			return instance;
		} catch (RuntimeException re) {
			log.error("get failed", re);
			throw re;
		}
	}

	public List findByExample(BBS instance) {
		log.debug("finding BBS instance by example");
		try {
			List results = getHibernateTemplate().findByExample(instance);
			log.debug("find by example successful, result size: "
					+ results.size());
			return results;
		} catch (RuntimeException re) {
			log.error("find by example failed", re);
			throw re;
		}
	}

	public List findByProperty(String propertyName, Object value) {
		log.debug("finding BBS instance with property: " + propertyName
				+ ", value: " + value);
		try {
			String queryString = "from BBS as model where model."
					+ propertyName + "= ?";
			return getHibernateTemplate().find(queryString, value);
		} catch (RuntimeException re) {
			log.error("find by property name failed", re);
			throw re;
		}
	}

	public List findByDefaultYn(Object defaultYn) {
		return findByProperty(DEFAULT_YN, defaultYn);
	}

	public List findByTitle(Object title) {
		return findByProperty(TITLE, title);
	}

	public List findByUserId(Object userId) {
		return findByProperty(USER_ID, userId);
	}

	public List findByTopSeq(Object topSeq) {
		return findByProperty(TOP_SEQ, topSeq);
	}

	public List findByParentSeq(Object parentSeq) {
		return findByProperty(PARENT_SEQ, parentSeq);
	}

	public List findBySortSeq(Object sortSeq) {
		return findByProperty(SORT_SEQ, sortSeq);
	}

	public List findByHits(Object hits) {
		return findByProperty(HITS, hits);
	}

	public List findByAttachYn(Object attachYn) {
		return findByProperty(ATTACH_YN, attachYn);
	}

	public List findByIsEditor(Object isEditor) {
		return findByProperty(IS_EDITOR, isEditor);
	}

	public List findByLocale(Object locale) {
		return findByProperty(LOCALE, locale);
	}

	public List findByCharset(Object charset) {
		return findByProperty(CHARSET, charset);
	}

	public List findBySummary(Object summary) {
		return findByProperty(SUMMARY, summary);
	}

	public List findByFocusYn(Object focusYn) {
		return findByProperty(FOCUS_YN, focusYn);
	}

	public List findByStatus(Object status) {
		return findByProperty(STATUS, status);
	}

	public List findAll() {
		log.debug("finding all BBS instances");
		try {
			String queryString = "from BBS";
			return getHibernateTemplate().find(queryString);
		} catch (RuntimeException re) {
			log.error("find all failed", re);
			throw re;
		}
	}

	public BBS merge(BBS detachedInstance) {
		log.debug("merging BBS instance");
		try {
			BBS result = (BBS) getHibernateTemplate().merge(detachedInstance);
			log.debug("merge successful");
			return result;
		} catch (RuntimeException re) {
			log.error("merge failed", re);
			throw re;
		}
	}

	public void attachDirty(BBS instance) {
		log.debug("attaching dirty BBS instance");
		try {
			getHibernateTemplate().saveOrUpdate(instance);
			log.debug("attach successful");
		} catch (RuntimeException re) {
			log.error("attach failed", re);
			throw re;
		}
	}

	public void attachClean(BBS instance) {
		log.debug("attaching clean BBS instance");
		try {
			getHibernateTemplate().lock(instance, LockMode.NONE);
			log.debug("attach successful");
		} catch (RuntimeException re) {
			log.error("attach failed", re);
			throw re;
		}
	}

	public static BBSDAO getFromApplicationContext(ApplicationContext ctx) {
		return (BBSDAO) ctx.getBean("BBSDAO");
	}
}